﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TagController.cs" company="ecblog.codeplex.com">
//   emrecoskun.net - ibrahimatay.com
// </copyright>
// <summary>
//   The tag controller
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace EcBlog.Areas.Admin.Controllers
{
    using System;
    using System.ComponentModel.Composition;
    using System.Linq;
    using System.Web.Mvc;

    using EcBlog.Data;
    using EcBlog.Models;
    using EcBlog.Properties;

    using Elmah;

    using Telerik.Web.Mvc;
    using Telerik.Web.Mvc.Extensions;

    /// <summary>
    /// The tag controller
    /// </summary>
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
#if !(DEBUG)
    [Filters.Authorize(PortalRole.Admin)]
#endif
    public class TagController : Controller
    {
        #region ctor

        private readonly IEcUnitOfWork unitOfWork;

        /// <summary>
        /// Initializes a new instance of the <see cref="TagController"/> class.
        /// </summary>
        /// <param name="unitOfWork">The unit of work.</param>
        [ImportingConstructor]
        public TagController(IEcUnitOfWork unitOfWork)
        {
            this.unitOfWork = unitOfWork;
        }

        #endregion

        #region Core Action Methods

        /// <summary>
        /// Gets the index view.
        /// </summary>
        /// <returns>The index view</returns>
        public ActionResult Index()
        {
            return this.View();
        }

        #endregion

        #region AJAX Tag Master Grid Action Methods

        /// <summary>
        /// Lists the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns>The list</returns>
        [GridAction(EnableCustomBinding = true)]
        public ActionResult List(GridCommand command = null)
        {
            if (command == null)
            {
                command = new GridCommand();
            }

            var list = this.unitOfWork.TagRepository.Get();
            return
                this.View(
                    list.ToGridModel(
                        command.Page,
                        command.PageSize,
                        command.SortDescriptors,
                        command.FilterDescriptors,
                        command.GroupDescriptors));
        }

        /// <summary>
        /// Inserts the specified tag.
        /// </summary>
        /// <param name="tag">The tag.</param>
        /// <param name="command">The command.</param>
        /// <returns>The list </returns>
        [HttpPost]
        [GridAction(EnableCustomBinding = true)]
        public ActionResult Insert(Tag tag, GridCommand command = null)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    this.unitOfWork.TagRepository.Create(tag);
                    this.unitOfWork.Save();
                }
                catch (Exception e)
                {
                    ErrorSignal.FromCurrentContext().Raise(e);
                    this.Response.StatusCode = 500;
                    this.Response.AppendHeader(
                        "message", string.Format(ModelLocalization.SaveUnitOfWorkError, tag.TagName, e.Message));
                }
            }

            return this.List(command);
        }

        /// <summary>
        /// Edits the specified tag.
        /// </summary>
        /// <param name="tag">The tag.</param>
        /// <param name="command">The command.</param>
        /// <returns>The list</returns>
        [HttpPost]
        [GridAction(EnableCustomBinding = true)]
        public ActionResult Edit(Tag tag, GridCommand command = null)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    this.unitOfWork.TagRepository.Update(tag);
                    this.unitOfWork.Save();
                }
                catch (Exception e)
                {
                    ErrorSignal.FromCurrentContext().Raise(e);
                    this.Response.StatusCode = 500;
                    this.Response.AppendHeader(
                        "message", string.Format(ModelLocalization.SaveUnitOfWorkError, tag.TagName, e.Message));
                }
            }

            return this.List(command);
        }

        /// <summary>
        /// Deletes the specified tag id.
        /// </summary>
        /// <param name="tagId">The tag id.</param>
        /// <param name="command">The command.</param>
        /// <returns>The list</returns>
        [HttpPost]
        [GridAction(EnableCustomBinding = true)]
        public ActionResult Delete(long tagId, GridCommand command)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    this.unitOfWork.TagRepository.Delete(tagId);
                    this.unitOfWork.Save();
                }
                catch (Exception e)
                {
                    ErrorSignal.FromCurrentContext().Raise(e);
                    this.Response.StatusCode = 500;
                    this.Response.AppendHeader(
                        "message", string.Format(ModelLocalization.SaveUnitOfWorkError, tagId, e.Message));
                }
            }

            return this.List(command);
        }

        #endregion

        #region AJAX Support Methods

        /// <summary>
        /// Checks the name of the duplicate tag.
        /// </summary>
        /// <param name="tagName">Name of the tag.</param>
        /// <param name="tagId">The tag id.</param>
        /// <returns>The validation result</returns>
        public ActionResult CheckDuplicateTagName(string tagName, long tagId)
        {
            var validateTitle =
                !this.unitOfWork.TagRepository.Get().Any(
                    c => c.TagId != tagId && c.TagName.ToLower() == tagName.ToLower());
            return this.Json(validateTitle, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Checks the duplicate tag slug.
        /// </summary>
        /// <param name="tagSlug">The tag slug.</param>
        /// <param name="tagId">The tag id.</param>
        /// <returns>The validation result</returns>
        public ActionResult CheckDuplicateTagSlug(string tagSlug, long tagId)
        {
            var validateTitle =
                !this.unitOfWork.TagRepository.Get().Any(
                    c => c.TagId != tagId && c.TagSlug.ToLower() == tagSlug.ToLower());
            return this.Json(validateTitle, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region disbose

        /// <summary>
        /// Releases unmanaged resources and optionally releases managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            this.unitOfWork.Dispose();
            base.Dispose(disposing);
        }

        #endregion
    }
}
